package gazzera.node.core.plugins.upload;

import gazzera.node.core.peer.*;
import gazzera.utils.*;

import java.util.*;
import java.util.concurrent.*;


class NodeQueue
{
	Queue<FileID> list = new LinkedBlockingDeque<FileID>();
}

public class UploadQueue
{
	private List<Pair<Node, NodeQueue>> queue = new LinkedList<Pair<Node,NodeQueue>>();
	
	
	public void add(Node node, FileID h)
	{
		for (Pair<Node, NodeQueue> p : queue)
		{
			if (p.a.equals(node))
			{
				// ok, we can add it here
				
				/*if(p.b.list.contains(h))
				{
					System.out.println("Already there!");
				}*/
				p.b.list.add(h);
				return;
			}
		}
		
		NodeQueue n = new NodeQueue();
		n.list.add(h);
		queue.add(new Pair<Node, NodeQueue>(node, n));
	}
	
	public void remove(Node node)
	{
		for (Pair<Node, NodeQueue> p : queue)
		{
			if (p.a.equals(node))
			{
				queue.remove(p);
				return;
			}
		}
	}
	
	public Pair<Node, FileID> poll(Collection<Node> avoid1, Collection<Node> avoid2)
	{
		for (Pair<Node, NodeQueue> p : queue)
		{
			if (avoid1.contains(p.a)||avoid2.contains(p.a))
			{
				// skip these ones
				System.out.println("Skipped "+p.a);
			}
			else
			{
				queue.remove(p);
				if (p.b.list.size() == 0)
				{
					System.out.println("size == 0 !!");
				}
				FileID h = p.b.list.poll();
				if (p.b.list.size() > 0)
				{
					// node has other stuff queued, re-enqueue
					queue.add(p);
				}
				else
				{
					System.out.println("remains ");
				}
				return new Pair<Node, FileID>(p.a, h);
			}
		}
		return null;	
	}
}
